﻿using M_Quality.API.Application.Command.RawMaterialQualityCommand;
using M_Quality.Domain;
using M_Quality.Repository.Impl;
using M_Quality.Repository.Interface;
using MediatR;
using System.Drawing;

namespace M_Quality.API.Application.CommandHandler.RawMaterialQualityCommandHandler
{
    public class AddRMQCommandHandler : IRequestHandler<AddRMQCommand, int>
    {
        private readonly IRawMaterialQualityRepository rawMaterialQualityRepository;
        protected readonly IQIQPRelationRepository qIQPRelationRepository;

        public AddRMQCommandHandler(IRawMaterialQualityRepository rawMaterialQualityRepository, IQIQPRelationRepository qIQPRelationRepository)
        {
            this.rawMaterialQualityRepository = rawMaterialQualityRepository;
            this.qIQPRelationRepository = qIQPRelationRepository;
        }

        public async Task<int> Handle(AddRMQCommand request, CancellationToken cancellationToken)
        {
        await rawMaterialQualityRepository.AddAsync(new RawMaterialQuality()
            {
                QualityName = request.QualityName,
                QualityNumber=request.QualityNumber,
                QualityTime=request.QualityTime,
                Qualityer=request.Qualityer,
                Supplier=request.Supplier,
                MaterialNumber=request.MaterialNumber,
                MaterialName=request.MaterialName,
                Unit=request.Unit,
                SpecificationsModel=request.SpecificationsModel,
                batchNumber=request.batchNumber,
                Size=request.Size,
                QualityType=request.QualityType,
                QualityScheme=request.QualityScheme,
                QualityS=request.QualityS,
                QualityNum=request.QualityNum,
                AcceptanceQuantity=request.AcceptanceQuantity,
                UnqualifiedQuantity=request.UnqualifiedQuantity,
                QualityInspector=request.QualityInspector,
                Remark=request.Remark,
                QualityResult=request.QualityResult,
            });
       var res= await rawMaterialQualityRepository.GetAsync(o => o.QualityNumber == request.QualityNumber);

            foreach (var item in request.QualityinspectionId)
            {
                await qIQPRelationRepository.AddAsync(new QIQPRelation()
                {
                RawMaterialQualityId = res.FirstOrDefault().RawMaterialQualityId,
                    QualityProjectId=item
            });
            }
            return 1;
}
    }
}
